import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import {
  Row, Col, Input, Button, Table, Card, message, Icon, Pagination, Tag,
  Radio, Form, Modal, Spin, Checkbox, Select, Switch, Tooltip, InputNumber,
} from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from '@/components/PageLoading';
import UserList from './userList';
import styles from './index.less';
import { getAuthority } from '@/utils/judgeAuthority';
import { resetDisabled, getBindInfo } from '@/services/user';
import UserSession from '@/UserSession';
const UserDrawer = React.lazy(() => import('./userDrawer'));
const { confirm } = Modal;

const { Search } = Input;
const { Option } = Select;
const CollectionCreateForm = Form.create({ name: 'form_in_modal' })(
  class extends React.Component {
    checkField(rule, value, callback) {
      const reg = /^[0-9a-zA-Z_.@]{1,}$/g;
      if (rule.field === 'userGuest') {
        if (value) {
          if (reg.test(value)) {
            if (value.length > 30 || value.length < 6) {
              callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
            } else {
              callback();
            }
          } else {
            callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
          }
        } else {
          callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
        }
      }
    }

    checkFieldForPassword(rule, value, callback) {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
      if (rule.field === 'password') {
        if (value) {
          if (reg.test(value)) {
            if (value.length > 30 || value.length < 6) {
              callback('支持8-20位大小写字母和数字');
            } else {
              callback();
            }
          } else {
            callback('支持8-20位大小写字母和数字');
          }
        } else {
          callback('支持8-20位大小写字母和数字');
        }
      }
    }
    handleChange(value, type) {
      this.props.handleChange(value, type);
    }

    render() {
      const {
        visible, onCancel, onCreate, form, userInfo, isEdit, loading,
        roles, authority, /* isCustomerOrder, type, */ handleClick, dataUserList,
      } = this.props;
      const { getFieldDecorator, getFieldValue } = form;
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 },
        },
      };
      const renderLabel = (label, tip) => {
        return (
          <label>
            {label}
            <Tooltip placement="topLeft" title={tip}>
              <Icon type="question-circle" style={{ verticalAlign: 'baseline', margin: '0 5px' }} />
            </Tooltip>
          </label>
        )
      };

      return (
        <Modal visible={visible} title="添加/编辑用户" okText="保存" onCancel={onCancel} onOk={onCreate} okButtonProps={{ disabled: authority === 1 }} width={700}>
          <Spin spinning={loading}>
            <Form {...formItemLayout}>
              {/* <Form.Item label="工号">
                {getFieldDecorator('jobNo', {
                  initialValue: userInfo.jobNo ? userInfo.jobNo : '',
                  rules: [{ required: true, message: '请输入用户工号' }],
                })(<Input placeholder="请输入用户的工号" />)}
              </Form.Item> */}
              <Form.Item label="用户昵称">
                {getFieldDecorator('nick', {
                  validateTrigger: ['onChange', 'onBlur'],
                  initialValue: userInfo.nick ? userInfo.nick : '',
                  rules: [{ required: true, message: '请输入用户昵称' }],
                })(<Input placeholder="请输入用户的昵称" disabled={authority === 1} maxLength={60} />)}
              </Form.Item>
              <Form.Item label="登录用户名">
                {getFieldDecorator('userGuest', {
                  initialValue: userInfo.username ? userInfo.username : undefined,
                  rules: [
                    { required: true, message: '登录用户名必填' },
                    { validator: this.checkField, },
                  ],
                })(
                  <Input disabled={!!userInfo.username || authority === 1} placeholder="登录用户名是用户的登录账号" maxLength={60} />
                )}
              </Form.Item>
              {
                userInfo.username ? '' : (
                  <Form.Item label="登录密码">
                    {getFieldDecorator('password', {
                      initialValue: userInfo.username ? '12345678abc' : undefined,
                      rules: [{ required: false, message: '登录密码必填' }, {
                        validator: this.checkFieldForPassword,
                      }],
                    })(
                      <Input.Password
                        placeholder="请输入用户的登录密码"
                        visibilityToggle={!userInfo.username}
                        disabled={!!userInfo.username || authority === 1}
                        maxLength={60}
                      />
                    )}
                  </Form.Item>
                )
              }
              <Form.Item label="手机号">
                {getFieldDecorator('phone', {
                  initialValue: userInfo.phone ? userInfo.phone : '',
                })(<Input placeholder="请输入用户的手机号" />)}
              </Form.Item>
              <Form.Item label={renderLabel("绑定用户信息", "用户发送工单推送消息，多个应用则需要绑定过个用户信息")}>
                <Row>
                  {dataUserList && dataUserList.length > 0 ? dataUserList.map((item, index) => {
                    return (
                      <Col key={index} style={{ margin: "0px 5px 5px 0", display: 'inline-block' }} className={styles.tag}>
                        <Tag>{item.clientEmptyInfo}</Tag>
                      </Col>
                    )
                  }) : null}
                </Row>
                <Button type="primary" onClick={() => handleClick(userInfo)}>绑定</Button>
              </Form.Item>
              {/* {UserSession.hasTicket() ? (
                <Form.Item label="是否为客服工单人员">
                  {getFieldDecorator('isCustomerOrder', {
                    initialValue: userInfo.isCustomerOrder == 1 ? true : userInfo.isCustomerOrder == 0 ? false : false,
                    valuePropName: "checked",
                    rules: [{ required: true }],
                  })(<Switch onChange={value => this.handleChange(value, "isCustomerOrder")} />)}
                </Form.Item>
              ) : null} */}
              {/* {getFieldValue('isCustomerOrder') ? (
                <Form.Item label="最大接待量">
                  {getFieldDecorator('maxReception', {
                    initialValue: userInfo.maxReception ? Number(userInfo.maxReception) : 0,
                    rules: [{ required: true }],
                  })(<InputNumber placeholder='请输入数字' min={0} style={{ width: '120px' }} />)}
                </Form.Item>
              ) : null} */}
              {/* <Form.Item label="是否为租户管理员">
                {getFieldDecorator('type', {
                  initialValue: userInfo.type == 0 ? false : userInfo.type == 1 ? true : false,
                  valuePropName: "checked",
                  rules: [{ required: true }],
                })(<Switch onChange={value => this.handleChange(value, "type")} disabled={userInfo && userInfo.createUser === '1'} />)}
              </Form.Item> */}
              {!(userInfo && userInfo.createUser === '1') ? (
                <Form.Item label="用户角色">
                  {getFieldDecorator('roleNames', {
                    initialValue: userInfo.roles ? userInfo.roles[0] ? userInfo.roles[0].id : '' : '',
                    rules: [{ required: true, message: '角色必填' }],
                  })(
                    <Radio.Group disabled={authority === 1}>
                      {roles.map((item, index) => {
                        return (
                          <div style={{ display: 'inline-block', width: 120, overflow: 'hidden', marginRight: 5, }} key={index} title={item.roleName}>
                            <Radio disabled={item.userStatus === 1} key={item.id} value={item.id}>{item.roleName}</Radio>
                          </div>
                        )
                      })}
                    </Radio.Group>
                  )}
                </Form.Item>
              ) : null}
            </Form>
          </Spin>
        </Modal>
      );
    }
  }
);

@connect(({ management, loading }) => ({
  management,
  loading: loading.effects['management/getUsers'],
}))
class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      notices: [],
      tableLoading: true,
      total: 0,
      visible: false,
      searchText: '',
      userInfo: {},
      isEdit: false,
      loading: true,
      pageSize: 10,
      auth: true,
      jy: false,
      roleList: [],
      // type: false,
      // isCustomerOrder: false,
      dataUserList: [],
    };
    this.columns = [
      {
        key: 'id',
        align: 'left',
        title: '登录用户名',
        dataIndex: 'username',
        width:200,
      },
      {
        key: 'nick',
        align: 'left',
        title: '用户昵称',
        dataIndex: 'nick',
        width:200,
      },
      {
        key: 'roles',
        align: 'left',
        title: '用户角色',
        dataIndex: 'roles',
        width:200,
        render: (roles) => {
          return roles.map(item => {
            return item.roleName + '  '
          })
        }
      },
      {
        key: 'createTime',
        align: 'left',
        title: '创建时间',
        dataIndex: 'createTime',
        width:200,
        render: dataIndex => {
          return moment(dataIndex).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        align: 'left',
        fixed:"right",
        width:200,
        render: (text, row) => {
          return (
            <div>
              <Button type="primary" size="small" style={{ marginRight: 5 }} onClick={() => this.queryUser(row)}>编辑</Button>
              <Button type="primary" size="small" style={{ marginRight: 5 }} onClick={() => this.resetUser(row)}>重置密码</Button>
              {row.disabled ? (
                <Button disabled={this.todo(row)} type="danger" size="small" style={this.sty(row)} onClick={() => this.resetDisabled(row, false)}>启用</Button>
              ) : (
                <Button disabled={this.todo(row)} type="primary" size="small" style={{ marginRight: 5 }} onClick={() => this.resetDisabled(row, true)}>停用</Button>
              )}
              <Button disabled={this.todo(row)} type="danger" size="small" style={this.qwe(row)} onClick={() => this.showDeleteConfirm(row)}>删除</Button>
            </div>
          );
        },
        width: '300px',
      },
    ];
  }

  componentDidMount() {
    this.getUsers();
  }

  showModal = () => {
    this.getRoleLists();
    const { form } = this.formRef.props;
    form.resetFields();
  };

  handleCancel = () => {
    this.setState({ visible: false, }, () => {
      this.setState({
        isEdit: false,
        userInfo: {},
        // type: false,
        dataUserList: [],
        // isCustomerOrder: false
      })
    });
  };

  handleCreate = () => {
    const { form } = this.formRef.props;
    const type = this.state.isEdit;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      if (type) {
        this.editUser(values);
      } else {
        this.addUser(values);
      }
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  onChangeForPage = number => {
    this.setState({ page: number, tableLoading: true, }, () => {
      this.getUsers();
    });
  };

  onShowSizeChangeForPage = (current, size) => {
    this.setState({ page: current, pageSize: size, tableLoading: true, }, () => {
      this.getUsers();
    });
  };

  getUsers = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'management/getUsers',
      payload: {
        current: this.state.page,
        size: this.state.pageSize,
        search: this.state.searchText,
      },
      callback: res => {
        this.setState({
          notices: res.records,
          total: res.total,
          tableLoading: false,
        });
      },
    });
  };

  addUser = obj => {
    const { dataUserList } = this.state;
    const { dispatch, currentUser } = this.props;
    const { form } = this.formRef.props;
    let roleNames = [];
    roleNames.push(obj.roleNames);
    let data = {
      username: obj.userGuest,
      nick: obj.nick,
      // jobNo: obj.jobNo,
      phone: obj.phone,
      password: obj.password,
      roleId: !obj.type ? roleNames : undefined,
      // isCustomerOrder: obj.isCustomerOrder ? 1 : 0,
      // maxReception: obj.isCustomerOrder ? obj.maxReception : undefined,
      // type: obj.type ? 1 : 0,
      clientEmptyId: dataUserList.map(item => item.id).join(','),
    };
    dispatch({
      type: 'management/addUser',
      payload: data,
      callback: res => {
        if (!res.code) {
          this.getUsers();
          this.setState({ visible: false, isEdit: false, userInfo: {} });
          form.resetFields();
          message.info(res.msg);
        }
      },
    });
  };

  delUser = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'management/delUser',
      payload: { id: row.id },
      callback: res => {
        message.success(res.msg);
        return this.getUsers();
      },
    });
  };

  showDeleteConfirm = row => {
    const that = this;
    confirm({
      title: `确认删除${row.nick}该账号吗`,
      content: '',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        that.delUser(row);
      },
      onCancel() {

      },
    });
  };

  resetUser = row => {
    const that = this;
    Modal.confirm({
      title: '确定重置密码吗？',
      okText: '确定',
      cancelText: '取消',
      okType: 'danger',
      onOk: () => {
        const { dispatch } = that.props;
        dispatch({
          type: 'management/resetUser',
          payload: { id: row.id },
          callback: res => {
            return message.info(res.data);
          },
        });
      }
    })
  };

  resetDisabled = async (row, type) => {
    let res = await resetDisabled({ id: row.id, disabled: type });
    console.log(res);
    if (res.data) {
      message.success('操作成功');
      this.getUsers();
    }
  }

  editUser = values => {
    const { dataUserList } = this.state;
    const { dispatch } = this.props;
    const arr = [];

    // if (typeof row.roleNames === 'string') {
    //   arr.push(row.roleNames);
    // }
    let roleNames = [];
    roleNames.push(values.roleNames)
    dispatch({
      type: 'management/editUser',
      payload: {
        id: this.state.userInfo.id,
        nick: values.nick,
        // jobNo: values.jobNo,
        phone: values.phone,
        roleId: !values.type ? roleNames : undefined,
        // isCustomerOrder: values.isCustomerOrder ? 1 : 0,
        // maxReception: values.isCustomerOrder ? values.maxReception : undefined,
        // type: values.type ? 1 : 0,
        clientEmptyId: dataUserList.map(item => item.id).join(','),
      },
      callback: res => {
        message.info(res.msg);
        this.setState({ visible: false, isEdit: false, userInfo: {} });
        this.getUsers();
        // if (res.status === true) {
        //   message.info(res.msg);
        //   this.setState({ visible: false, isEdit: false, userInfo: {} });
        //   this.getUsers();
        // } else {
        //   this.setState({ auth: false, visible: false, isEdit: false, userInfo: {} });
        // }
      },
    });
  };

  queryUser = row => {
    const { dispatch, currentUser } = this.props;
    const { form } = this.formRef.props;
    form.resetFields();
    this.setState({ visible: true, isEdit: true, loading: true });
    this.getRoleLists();
    const that = this;
    dispatch({
      type: 'management/getUserById',
      payload: { id: row.id },
      callback: res => {
        that.setState({
          userInfo: res,
          loading: false,
          // type: res.type == 0 ? false : res.type == 1 ? true : false,
          // isCustomerOrder: res.isCustomerOrder == 1 ? true : res.isCustomerOrder == 0 ? false : false,
        }, () => {
          this.getUserList(res);
        });
      },
    });
  };

  getUserList = async (userInfo) => {
    let res = await getBindInfo({ clientEmptyId: userInfo.clientEmptyId });
    // console.log(res);
    this.setState({ dataUserList: res });
  }

  getRoleLists = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'management/getRoleLists',
      payload: { current: 1, size: 99999 },
      callback: res => {
        if (res.records.length > 0) {
          this.setState({ roleList: res.records, visible: true, loading: false, });
        } else {
          return message.info('请先添加角色');
        }
      },
    });
  };

  setSearch = val => {
    this.setState({ searchText: val, page: 1, }, () => {
      this.getUsers();
    });
  };

  setClassName = (record, index) => {
    const { currentUser } = this.props;
    if (currentUser.nick === record.nick) {
      return styles.red;
    }
    // this.setState({jy:false})
  };

  todo = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick && currentUser.id === row.id) {
      return true;
    }
  };

  sty = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick || row.type === 1) {
      return { marginRight: 5 };
    }
    return { marginRight: 5, backgroundColor: 'orange', color: '#fff', borderColor: 'orange' };
  };

  qwe = row => {
    const { currentUser } = this.props;
    if (currentUser.nick === row.nick || row.type === 1) {
      return { marginRight: 5 };
    }
    return { marginRight: 5, backgroundColor: 'red', color: '#fff' };
  };

  handleChange = (value, type) => {
    this.setState({ [type]: value });
  }

  handleClick = (userInfo) => {
    this.UserList.infoData(userInfo);
  }

  setUserList = (data) => {
    this.setState({ dataUserList: data }, () => {
      this.UserList.cancelModal()
    });
  }

  render() {
    const { notices, tableLoading, page, total, pageSize, userInfo, isEdit, loading, roleList, dataUserList } = this.state;

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Card bordered={false}>
            <div style={{ marginBottom: 10, borderBottom: '1px solid lightgrey', paddingBottom: 10 }}>
              <span style={{ fontSize: 16, color: '#000', borderLeft: '5px solid #13c2f3', paddingLeft: 10, }}>
                账号管理({this.state.total})
              </span>
            </div>
            <Row style={{ marginBottom: 10 }}>
              <Col span={4}>
                <Button type="primary" icon="plus" style={{ marginRight: 5 }} onClick={this.showModal} disabled={getAuthority(this.props.route.authority) === 1}>添加</Button>
              </Col>
              <Col offset={16} span={4}>
                <Search placeholder="请输入登录用户名" onSearch={value => this.setSearch(value)} />
              </Col>
            </Row>
            <div>
              <Table
                // rowClassName={this.setClassName}
                columns={this.columns}
                dataSource={notices}
                rowKey="id"
                pagination={{
                  // 分页
                  total,
                  pageSize, // 显示几条一页
                  defaultPageSize: page, // 当前页
                  showSizeChanger: true, // 是否显示可以设置几条一页的选项
                  showQuickJumper: true,
                  onChange: this.onChangeForPage,
                  onShowSizeChange: this.onShowSizeChangeForPage,
                }}
                loading={tableLoading}
                scroll={{x:"auto"}}
              />
            </div>

            <CollectionCreateForm
              wrappedComponentRef={this.saveFormRef}
              visible={this.state.visible}
              onCancel={this.handleCancel}
              onCreate={this.handleCreate}
              userInfo={userInfo}
              roles={roleList}
              isEdit={isEdit}
              loading={loading}
              handleChange={this.handleChange}
              // type={this.state.type}
              handleClick={this.handleClick}
              dataUserList={dataUserList}
              // isCustomerOrder={this.state.isCustomerOrder}
              authority={getAuthority(this.props.route.authority)}
            />
            {/*<UserDrawer visible={this.state.visible}/>*/}
            <UserList onRef={ref => this.UserList = ref} setUserList={this.setUserList} />
          </Card>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Users);
